var express = require('express')
var router = express.Router()

//导入数据库操作模块
var exec = require('../db')
//导入调试的标记
const {
  debug
} = require('../config')

// 查询
router.get('/', async function (req, res) {

  // 搜索多条数据时, 显示的字段:
  let select_fields =
    'article_id,user_id,article_name,id'
  //声明sql语句变量
  let sql
  // 获取全部数据列表 GET /articles
  if (JSON.stringify(req.query) == '{}') {
    sql = `SELECT ${select_fields} FROM job_tb,category_tb where job_tb.category_id=category_tb.id && deleted_time is null`
  }

  // 根据标题模糊查询获取数据列表 GET /articles?title=总结
  else if (req.query.title) {
    sql = `SELECT ${select_fields} FROM job_tb job_tb,category_tb where job_tb.category_id=category_tb.id && title like '%${req.query.title}%' && deleted_time is null`
  }


  // 根据作者id获取数据 GET /articles?user_id=2
  else if (req.query.user_id) {
    sql = `SELECT ${select_fields} FROM collect_tb where collect_tb.user_id = ${req.query.user_id}  `
  }


  // 数据响应
  try {
    res.send({
      code: 0,
      msg: '查询成功',
      result: await exec(sql),
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '失败',
      result: debug ? err : '',
    })
  }
})

// 增加数据 post /articles
router.post('/', async (req, res) => {
  let {
    user_id,
    article_id,
    article_name
  } = req.body

  //查询语句
  let sql = `INSERT INTO collect_tb (user_id,article_id,article_name) VALUES ('${user_id}','${article_id}','${article_name}')`

  try {
    //返回
    const data = await exec(sql)
    res.send({
      code: 0,
      msg: '添加成功',
      result: data.insertId
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '添加失败',
      result: debug ? err : ''
    })
  }
})

// 根据id修改博客内容 PUT /articles?id=2
// 根据id修改博客是否推荐 PUT /articles?id=2
router.put('/', async (req, res) => {
  // console.log('req.body', req.body)

  // 获取请求数据
  let body = req.body
  // 过滤需要修改的数据
  let bodyfilter = ''
  for (let key in body) {
    if (body[key] !== '') {
      bodyfilter += `${key}='${body[key]}',`
    }
  }
  //删除句尾逗号
  bodyfilter = bodyfilter.slice(0, bodyfilter.length - 1)

  //修改内容
  let sql = `UPDATE job_tb SET ${bodyfilter} where id = ${req.query.id}`

  try {
    let data = await exec(sql)
    res.send({
      code: 0,
      msg: '修改成功',
      result: ''
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '修改失败',
      result: debug ? err : ''
    })
  }
})


// 软删除 DELETE /articles?id=1
router.delete('/:id', async (req, res) => {
  sql = `delete from collect_tb where id= ${req.params.id}`

  //响应
  try {
    let data = await exec(sql)
    res.send({
      code: 0,
      msg: '删除成功',
      result: ''
    })
  } catch (err) {
    res.send({
      code: 1,
      msg: '删除失败',
      result: debug ? err : ''
    })
  }
})

module.exports = router